<?php
class UsersController extends AppController {
	var $helpers = array('Html', 'Form','Session');
	var $uses = array('User','Acrpermission','Acpermission');
	
	public function beforeFilter() {
		$this->Auth->allow("login, logout");
		$this->layout = 'login';
		// $this->request->
		//debug(AuthComponent::password('admin'));
	}
	
	public function signup () {
		
	}
	
	public function login() {
	    if ($this->request->is('post')) {
	        if ($this->Auth->login()) {
	        	$this->Session->write('User', $this->Auth->user());
				// load permissions
				$permissions = $this->Acrpermission->loadPermissions();
				$this->Session->write("permission", $permissions);
				
	            return $this->redirect($this->Auth->redirect());
	        } else {
	            $this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
	        }
	    } 
	}
	
	public function logout() {
 	   $this->redirect($this->Auth->logout());
	}
	
	public function updateProfile() {
	
	}
	
	public function forgotPassword() {
	
	}
	
	public function changePassword() {
		$this->layout = 'quanly';
		if ($this->request->is('post')) {
			$user = $this->User->findById($this->Auth->user('id'));
			// debug($user);
			if($user['User']['password'] != AuthComponent::password($this->request->data['User']['oldpassword'])) {
				//debug("Invalide old password");
				$this->User->invalidate('User.oldpassword', __('Mật khẩu cũ không hợp lệ', true));
			} else if (empty($this->request->data['User']['newpassword'])) {
				$this->User->invalidate('newpassword', __('Xin vui long nhập mật khẩu mới', true));
			} else {
				$user['User']['password'] = $this->request->data['User']['newpassword'];
				$user['User']['repassword'] = $this->request->data['User']['renewpassword'];
				
				if ($this->User->save($user)) {
					$this->redirect(array("action" => 'changePassword'));
				} 
			}
			
			$errors = $this->User->validationErrors;
			$this->set("errors", $errors);
		}
	}
}
